<script lang="ts" setup>
import { ref } from 'vue';
import ServerApi from '../api/webhookServer.js'
import { ElMessage, ElMessageBox } from 'element-plus'

const serverApi = new ServerApi();

const resData = ref([]); // 存储请求数据的数组

const itemData = ref({});

const itemHeader = ref({}); 

const httpStatus = ref({}); 

const port = ref(8080); // 当前监听的端口号，默认为8080
// 获取当前端口号的方法（根据具体需求实现）
function getCurrentPort() {
  return serverApi.getServerPort()
}

function refreshServerStatus() {
  httpStatus.value = serverApi.getServerStatus()
}

function stop(){
  serverApi.closeServer()
}

// 清空历史记录的方法（按钮点击事件）
function clearHistory() {
  // if (!confirm('确认清空所有记录？')) return; // 弹出确认框询问用户是否确认清空记录
  ElMessageBox.confirm(
    '确认清空所有记录？',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      resData.value = serverApi.clearServerHistory()
      itemData.value = {}
      itemHeader.value = {}
    })
    .catch(() => {
    })
  // resData.value = serverApi.clearServerHistory()
  // itemData.value = {}
  // itemHeader.value = {}
}

// 定时触发刷新请求列表
setInterval(() => {
  var res = serverApi.getServerHistory()
  resData.value = [...res]
  httpStatus.value = serverApi.getServerStatus()
}, 1000);

function start(){
  serverApi.createServer(port.value)
}

function showItem(item){
  itemData.value = item
  itemHeader.value = item.headers
}

function truncateUrl(method: String, url: string): string {
  const queryIndex = url.indexOf('?');
  if (queryIndex !== -1) {
    url = url.substring(0, queryIndex);
  }
  url = url.length > 20 ? url.substring(0, 20) + '...' : url;
  return `[${method}] ${url} `;
}
</script>

<template>
  <el-card class="main-card">
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="6">
        <el-input
          :disabled="httpStatus"
          v-model="port"
          placeholder="请输入端口号"
        />
      </el-col>
      <el-col :span="2">
        <el-button
          v-if="httpStatus"
          type="primary"
          @click="stop"
        >
          暂停
        </el-button>
        <el-button
          v-else
          type="success"
          @click="start"
        >
          启动
        </el-button>
      </el-col>
      <el-col :span="6">
        <el-button
          type="danger"
          @click="clearHistory"
        >
          清空历史记录
        </el-button>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="history-card">
          <template #header>
            <div class="card-header">
              <span>请求监听列表</span>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="(item, index) in resData"
              :key="index"
              :timestamp="item.timestamp" @click="showItem(item)"
            >
                <el-tooltip :content="item.url" placement="top">
                  <div>
                    {{ truncateUrl(item.method, item.url) }}
                  </div>
                </el-tooltip>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>

      <el-col :span="18">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>请求详情</span>
            </div>
          </template>
          <h4>请求URL: {{ itemData.url }}</h4>
          <h4>请求方式：{{ itemData.method }}</h4>
          <h4>请求时间：{{ itemData.timestamp }}</h4>
          <h4>请求头信息：</h4>
          <el-row v-if="Object.keys(itemHeader).length > 0" style="margin-top: 20px;">
            <el-col :span="24">
              <el-card>
                <div v-for="(value, key) in itemHeader" :key="key">
                  <strong>{{ key }} : </strong> {{ value }}
                </div>
              </el-card>
            </el-col>
          </el-row>
          <h4>请求体：</h4>
          <div v-if="itemData.body" style="margin-top: 20px;">
            <el-card>
              {{ itemData.body }}
            </el-card>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </el-card>
</template>

<style scoped>
.main-card {
  margin: 20px;
  padding: 20px;
}
.history-card,
.detail-card {
  height: 500px;
  width: 100%;
  overflow-y: auto;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>